package dao;

import entity.User;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class RegisterDao {

    /**
     * 新增用户
     *
     * @params: [user 新增对象]
     * @return: boolean（true:成功，fase:失败）
     */
    public boolean insert(User user) {
        boolean insert = false;
        String sql = "insert `user`(`user`, `password`, `email`, `name`, `phone`, `address`) values(?, ?, ?, ?, ?, ?)";

        try {
            // 获取数据库连接
            Connection conn = DBUtil.getConn();

            // SQL域处理
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUser());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getEmail());
            ps.setString(4, user.getName());
            ps.setString(5, user.getPhone());
            ps.setString(6, user.getAddress());

            // 执行
            insert = ps.executeUpdate() != 0 ? true : false;
            DBUtil.close(ps, conn);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("用户添加失败");
        } finally {
            return insert;
        }
    }

}
